<?php
/**
 * 后台Index相关
 */
namespace Admin\Controller;
use Think\Controller;
use Think\Exception;

class AdminController extends CommonController {


    public function index() {
        $data = array();
        if($_SESSION['adminUser']['id'] != 1){
            $data['id'] = $_SESSION['adminUser']['id'];
        }
        $user = D('Admin')->getuser($data);
        $this->assign('user', $user);
        $this->display();
    }

    public function add() {

        // 保存数据
        if(IS_POST) {

            if(!isset($_POST['username']) || !$_POST['username']) {
                return show(0, '用户名不能为空');
            }
            if(!isset($_POST['password']) || !$_POST['password']) {
                return show(0, '密码不能为空');
            }
            $_POST['password'] = getMd5Password($_POST['password']);
            // 判定用户名是否存在
            $admin = D("Admin")->getAdminByUsername($_POST['username']);
            if($admin && $admin['status']!=2) {
                return show(0,'该用户存在');
            }

            // 新增
            $id = D("Admin")->insert($_POST);
            if(!$id) {
                return show(0, '新增失败');
            }
            return show(1, '新增成功');
        }
        $this->display();
    }

    public function setStatus() {
        $data = array(
            'id'=>intval($_POST['id']),
            'status' => 2,
        );
        return parent::setStatus($_POST,'Admin');
    }

    public function edit() {
        $id=$_GET['id'];
        $user = D("Admin")->getAdminByAdminId($id);
        $this->assign('user',$user);
        $this->display();
    }

    public function save() {
        $id=$_POST['id'];
        if($_POST['password']){
            $data['password'] = getMd5Password($_POST['password']);
        }
        $data['realname'] = $_POST['realname'];
        $data['email'] = $_POST['email'];
        $data['thumb'] = $_POST['thumb'];

        try {
            $id = D("Admin")->updateByAdminId($id, $data);
            if($id === false) {
                return show(0, '修改失败');
            }
            return show(1, '修改成功');
        }catch(Exception $e) {
            return show(0, $e->getMessage());
        }
    }

}